#include <linux/input.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include "touch.h"

int touch_fd = -1;
int x_read = -1;
int y_read = -1;

//打开触摸屏
int init_touch_screen()
{
	touch_fd = open("/dev/input/event0", O_RDWR);
	if (-1 == touch_fd)
    {
        perror("open touch failed");
		return -1;
    }
	
	return 0;
}

//关闭触摸屏
int uninit_touch_screen()
{
	int res = close(touch_fd);
	if (-1 == res)
    {
        perror("close touch failed");
		return -1;
    }
	
	return 0;
}

//获取用户触摸的坐标值x,y返回x,y的值	
int get_xy()
{
	int x = -1;
	int y = -1;
	//定义了一个结构体去保存读取到的数据
	struct input_event ts;
	
	//不停的去读取触摸事件
	while(1)
	{
		int res = read(touch_fd,&ts,sizeof(ts));
		if(res != sizeof(ts))//加入读取错误
		{
			//结束这次循环继续
			continue;
		}
		
		// 为按键事件并且为触摸点击	触摸屏事件
		// if(ts.type == EV_KEY && ts.code == BTN_TOUCH)
		// {
			// if(ts.value == 1)
			// {
				// printf("press\n");
			// }
			// else if(ts.value == 0)
			// {
				// printf("relse\n");
			// }
		// }
		
		if(ts.type == EV_ABS)
		{
			if(ts.code == ABS_X)
			{
				x = ts.value*800/1024;
			}
			else if(ts.code == ABS_Y)
			{
				y = ts.value*480/600;
			}
		}
		
		if(x>=0&&y>=0)
		{
			x_read = x;
			y_read = y;
			printf("(%d,%d)\n",x_read,y_read);
			break;
		}
	}
}	

//滑动触摸	
int slide_touch()
{
	int read_x1 = -1, read_y1 = -1;
	int read_x2 = -1, read_y2 = -1;
	
	struct input_event ts;
	
	while(1)
	{
		read(touch_fd, &ts, sizeof(struct input_event));
		
		if(ts.type == EV_KEY && ts.code == BTN_TOUCH)
		{
			// if(ts.value == 1)
			// {
				// printf("press\n");
			// }
			// else if(ts.value == 0)
			// {
				// printf("relse\n");
			// }
			if(ts.value == 0)
			{
				//printf("relse\n");
				if(read_x2>=0 && read_y2>=0)
				{
					break;
				}
			}
		}
		
		if(ts.type == EV_ABS)
		{
			if(ts.code == ABS_X)
			{
				if(read_x1>=0 && read_y1>=0)
				{
					read_x2 = ts.value*800/1024;
				}
				else
				{
					read_x1 = ts.value*800/1024;
				}
			}
			if(ts.code == ABS_Y)
			{
				if(read_x1>=0 && read_y1>=0)
				{
					read_y2 = ts.value*480/600;
				}
				else
				{
					read_y1 = ts.value*480/600;
				}
			}
		}
	}
	
	//判断滑动方向
	if(abs(read_x1-read_x2)>abs(read_y1-read_y2)&&read_x1<read_x2)//右滑
	{
		printf("you\n");
		return 1;
	}
	else if(abs(read_x1-read_x2)>abs(read_y1-read_y2)&&read_x1>read_x2)//左滑
	{
		printf("zuo\n");
		return 2;
	}
	else if(abs(read_x1-read_x2)<abs(read_y1-read_y2)&&read_y1>read_y2)//上滑
	{
		printf("shang\n");
		return 3;
	}
	else if(abs(read_x1-read_x2)<abs(read_y1-read_y2)&&read_y1<read_y2)//下滑
	{
		printf("xia\n");
		return 4;
	}
	
}

